<template>
    <div class="campOn">
        <van-nav-bar title="预占号申请" style="background: transparent"></van-nav-bar>
        <div class="">
            <van-list class="list" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-loading v-if="loading" size="24px" color="#1890ff" vertical>加载中...</van-loading>
                <div v-else>
                    <van-cell class="list-item" v-for="item in campOnList" :key="item.id">
                        <template #default>
                            <div class="blue-bar"></div>
                            <div style="padding:0 18px 18px 18px;display: flex;flex-direction: column;gap: 10px;">
                                <div><span class="groupTitle">手机号：</span><span class="font-bold text-16px">{{
                                    item.mobile }}</span></div>
                                <div><span class="groupTitle">类型：</span>{{ typeList[item.mobileType - 1] }}</div>
                                <div><span class="groupTitle">预占剩余时间：</span>{{ item.restTime }}
                                </div>
                                <van-button type="primary" size="small" @click="apply(item)"
                                    style=" font-weight: bold;font-size: 14px;letter-spacing: 2px;border-radius: 10px;">申请</van-button>
                            </div>
                        </template>
                    </van-cell>
                </div>

            </van-list>
        </div>
        <van-dialog v-model:show="visible" title="">
            <div v-html="htmlText"></div>
        </van-dialog>
        <van-tabbar v-model="active" placeholder>
            <van-tabbar-item icon="search" @click="goToPage('/choosePhone')">号码查询</van-tabbar-item>
            <van-tabbar-item icon="orders-o" @click="goToPage('/campOn')">预占列表</van-tabbar-item>
        </van-tabbar>
    </div>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router";
import { getOccupiedLuckMobile, applyById, getRichText } from "../api/phone"
import { ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import { MobileType, TriangleUrl } from "@/constant/constant";
import { debounce } from "../utils/index";
import { formatTime } from "../utils/util";
import { Toast } from "vant";

import { useStore } from 'vuex'
const { proxy } = getCurrentInstance();
const finished = ref(false);
const loading = ref(true)
const pageSize = ref(10)
const pageNum = ref(1)
const campOnList = ref([])
const visible = ref(false)
const htmlText = ref()
const queryData = ref({

})
const store = useStore()
const typeList = ["普通号码", "协议号码", "家业集中申请协议号码"]
const router = useRouter()
const active = ref(1);
const wgtUserId = ref(store.getters.wgtUserId);
let timer = null;
onMounted(() => {
    timer = setInterval(formatNumberObject, 1000);
    getRichText()
        .then((res) => {
            if (res.data.code == 200) {
                htmlText.value = res.data.data.list[0].fullText;
            }
            console.log(htmlText.value)
        })
        .catch((err) => {
            console.log("err:", err);
        });
});

onBeforeUnmount(() => {
    clearInterval(timer);
});
const queryByCond = () => {
    return new Promise((resolve, reject) => {
        getOccupiedLuckMobile(pageSize.value, pageNum.value)
            .then((response) => {
                loading.value = false
                const data = response.data
                if (data.code === 200) {
                    campOnList.value = campOnList.value.concat(data.data.list);
                    if (data.data.isLastPage) {
                        finished.value = data.data.isLastPage;
                        return;
                    }
                    pageNum.value += 1;
                } else {
                    Toast.fail(data.message);
                    reject();
                }
            })
            .catch((error) => {
                loading.value = false
                if (error.message !== "") {
                    Toast.fail(error.message);
                }
                reject(error);
            });
    });
}
const goToPage = (path) => {
    router.push(path)
}
function formatNumberObject() {
    campOnList.value?.forEach((item) => {

        const currentTime = new Date();
        const endTime = new Date(item.endTime);
        const restTime = (endTime.getTime() - currentTime.getTime()) / 1000;
        const days = parseInt((restTime / 86400).toString()); // 天  24*60*60*1000
        const hours = parseInt((restTime / 3600).toString()) - 24 * days; // 小时 60*60 总小时数-过去的小时数=现在的小时数
        const minutes = parseInt(((restTime % 3600) / 60).toString()); // 分钟 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
        const seconds = parseInt((restTime % 60).toString()); // 以60秒为一整份 取余 剩下秒数

        const restTimeStr = formatTime(hours + ":" + minutes + ":" + seconds);
        item.restTime = restTimeStr.startsWith("-") ? "00:00:00" : restTimeStr;
    });
}
const onLoad = debounce(() => {
    queryByCond();
    formatNumberObject();
}, 1000);

const showModal = () => {
    visible.value = true;
};
const refresh = () => {
    clearInterval(timmer);
    campOnList.value = [];
    queryByCond()
}
const apply = (target) => {
    if (
        campOnList.value.filter((item) => item.id === target.id)[0]
            .mobileType === MobileType.Protocol
    ) {
        //协议号码只弹窗提示
        showModal();
        refresh();
        return;
    }
    //普通号码预占
    applyById(target.id, target.mobile)
        .then((res) => {

            if (res.data.code === 200) {
                //普通号码跳转
                if (
                    campOnList.value.filter((item) => item.id === target.id)[0]
                        .mobileType === MobileType.Normal
                ) {

                    // window.navigator.clipboard
                    //   .writeText(selectedMobile.value)
                    //   .then((res) => {
                    //     Toast("号码已复制到剪贴板");
                    //     if (wgtUserId.value) {
                    //       location.href = TriangleUrl + "?userId=" + wgtUserId.value;
                    //     } else {
                    //       location.href = TriangleUrl;
                    //     }
                    //   });


                    proxy.$copyText(target.mobile).then(
                        function (e) {
                            debugger
                            Toast.success("号码已复制到剪贴板");
                            if (wgtUserId.value) {
                                location.href = TriangleUrl + "?userId=" + wgtUserId.value;
                            } else {
                                location.href = TriangleUrl;
                            }
                        },
                        function (e) {
                            Toast.fail("复制失败");
                        }
                    );

                }
            }
        })
        .catch((err) => {
            console.log(err)
            Toast.fail(err.message);
        });
};

</script>
<style scoped>
.blue-bar {
    background: #1989fa;
    width: 4px;
    height: 16px;
    display: inline-block;
    position: absolute;
    top: 3px;
    border-radius: 5px;
}

.list-item {
    margin: 16px 16px 0 16px;
    border-radius: 8px;
    width: auto;
}
</style>